<template>
  <div class="mapping">
    <Pedding ref="pedding" v-show="!mapState.area" @start="start" @stop="stop" @pause="pause" @contenue="contenue"
      :startPos="mapState.startPos" :currentPos="mapState.currentPos" :distance="state.distance"
      :isAccurate="state.isAccurate" :isDrawing="state.isDrawing" />
    <Save v-show="mapState.area" @toDetail="emits('toDetail')" :pointList="pointList" @setColor="setColor"
      :area="mapState.area"></Save>
    <!-- <Save @setColor="setColor" :area="mapState.area"></Save> -->
  </div>
</template>

<script setup>
import Pedding from './pedding.vue'
import Save from '@/components/mapping/save.vue'
import { addPolygon, getLocation, updateSite } from '@/api/map'
import { reactive, ref, onMounted, nextTick, defineEmits, defineExpose, watch, onUnmounted } from 'vue'
import { mapState, defaultPolygonOption, handleCenter } from '@/store/index'

const state = reactive({
  distance: 0,
  isDrawing: false,
  isAccurate: false
})

defineExpose({
  state
})

const emits = defineEmits(['toDetail', 'getPolygons', 'setCurrentPosMarkPos'])

const pedding = ref();

let line;
let polygonTool;

// let pointList = [
//   { latitude: 30.412674162115806,  longitude: 104.08834977431684 },
//   { latitude: 30.407735466107866, longitude: 104.08794791241519 },
//   { latitude: 30.40782211205115, longitude: 104.09543259033398 },
//   { latitude: 30.412110990105433, longitude: 104.09759259805452 },
//   { latitude: 30.4126741621158,  longitude: 104.088349774316 },
// ];
let pointList = []
let list = []


const pointMarder = {
  s_p_marker: {
    marker: new T.Marker(new T.LngLat(0, 0), {
      icon: new T.Icon({
        iconUrl: require('@/assets/img/startPoint.png'),
        iconSize: new T.Point(79, 48),
        iconAnchor: new T.Point(39.5, 48)
      })
    }),
    has: false,
    remove() {
      if (!this.has) return;
      this.has = false;
      window.map.removeOverLay(this.marker)
    },
    add() {
      if (this.has) return;
      if (pointList.length < 1) return;
      const { latitude, longitude } = pointList[0]
      this.marker.setLngLat(new T.LngLat(longitude, latitude))
      this.has = true;
      window.map.addOverLay(this.marker)
    }
  },
  c_p_marker: {
    marker: new T.Marker(new T.LngLat(0, 0), {
      icon: new T.Icon({
        iconUrl: require('@/assets/img/currentPoint.png'),
        iconSize: new T.Point(18, 22.5),
        iconAnchor: new T.Point(9, 22.5),
        title: '1000', 
        zIndexOffset: 1000
      }),
    }),
    has: false,
    remove() {
      if (!this.has) return;
      this.has = false;
      window.map.removeOverLay(this.marker)
    },
    add() {
      if (this.has) return;
      this.has = true;
      window.map.addOverLay(this.marker)
    },
    set() {
      if (pointMarder.e_p_marker.has) {
        pointMarder.e_p_marker.has = false;
        window.map.removeOverLay(pointMarder.e_p_marker.marker);
      }
      if (pointList.length < 2) return
      const { latitude, longitude } = pointList[pointList.length - 1]
      this.marker.setLngLat(new T.LngLat(longitude, latitude))
      this.add();
    }
  },
  e_p_marker: {
    marker: new T.Marker(new T.LngLat(0, 0), {
      icon: new T.Icon({
        iconUrl: require('@/assets/img/endPoint.png'),
        iconSize: new T.Point(79, 48),
        iconAnchor: new T.Point(39.5, 48),
        title: '1000', 
        zIndexOffset: 1000
      })
    }),
    has: false,
    remove() {
      if (!this.has) return;
      this.has = false;
      window.map.removeOverLay(this.marker)
    },
    add() {
      if (this.has) return;
      this.has = true;
      window.map.addOverLay(this.marker)
    },
    set() {
      if (pointList.length < 2) return
      if (pointMarder.c_p_marker.has) {
        pointMarder.c_p_marker.has = false;
        window.map.removeOverLay(pointMarder.c_p_marker.marker);
      }
      const { latitude, longitude } = pointList[pointList.length - 1]
      this.marker.setLngLat(new T.LngLat(longitude, latitude))
      this.add();
    }
  }
}

const start = async () => {
  try {
    state.isDrawing = true;
    initLine();
    await getLoc();
  } catch (error) {
    console.error(error);
    alert(error)
  }


  // 模拟走路
  // _s();
}

const initLine = () => {
  line = new T.Polyline([])
  window.map.addOverLay(line);
}

const getLoc = async () => {
  try {
    const res = await getLocation();
    if (!res) return;
    const { latitude, longitude, accuracy } = res
    if (Number(accuracy) > 10) {
      return state.isAccurate = false
    } else {
      state.isAccurate = true;
    }
    mapState.zoom = 18
    window.map.centerAndZoom(new T.LngLat(longitude, latitude), mapState.zoom)
    drawLine({ latitude, longitude })
    pointList.push({ latitude, longitude })
    if (!mapState.startPos) {
      pointMarder.s_p_marker.add()
      mapState.startPos = `${Number(pointList[0].latitude).toFixed(4)}, ${Number(pointList[0].longitude).toFixed(4)}`
    }
    if (pedding.value.isClose2End) {
      pointMarder.e_p_marker.set();
    } else {
      pointMarder.c_p_marker.set();
    }
    emits ('setCurrentPosMarkPos', {
      longitude, latitude
    }) 
  } catch (error) {
    console.error(error);
    alert(error)
  } finally {
    if (!state.isDrawing) return;
    setTimeout(getLoc, 1000)
  }
}

let int;
const _s = () => {
  const _ps = [...pointList]
  int = setInterval(() => {
    if (_ps.length) {
      const p = _ps.pop();
      drawLine(p)
    } else {
      if (int) {
        clearInterval(int)
        int = null;
      }
    }
  }, 200);
}

// 划线
const drawLine = (pos = {
  latitude: '',
  longitude: ''
}) => {
  // 划线
  list.push(new T.LngLat(pos.longitude, pos.latitude))
  line.setLngLats(list)
  // 标定当前坐标
  mapState.currentPos = `${Number(pos.latitude).toFixed(4)}, ${Number(pos.longitude).toFixed(4)}`
  // 计算已经走过的距离
  if (list.length > 2) {
    state.distance = (Number(state.distance) + (list[list.length - 2].distanceTo(list[list.length - 1]) / 1000)).toFixed(2)
  }
}

// 当遇上异常结束时暂停
const pause = () => {
  state.isDrawing = false;
}

const contenue = () => {
  state.isDrawing = true;
  getLoc();
}

const stop = async (isFinished) => {
  state.isDrawing = false;
  try {
    if (!isFinished) {
      window.map.removeOverLay(line)
      reset()
    } else {
      if (!polygonTool)
        polygonTool = new T.PolygonTool(map);
      const _quareMeters = Number(polygonTool.getArea(list))
      const area = (_quareMeters / 666.6666).toFixed(2)
      const { data: id } = await addPolygon({
        area,
        config: JSON.stringify({
          points: pointList,
          config: {
            ...defaultPolygonOption,
          }
        })
      })
      mapState.currentId = id
      mapState.area = area
      emits('getPolygons', () => {
        const currentPolygon = window.map.getOverlays().find(v => v.options.id === id)
        mapState.currentPolygon = currentPolygon
        handleCenter();
      })
    }
  } catch (error) {
    console.error(error);
    alert(error)
  }

}

const setColor = (color) => {
  mapState.currentPolygon.setFillColor(color)
  mapState.currentPolygon.setColor(color)
}


const reset = () => {
  mapState.currentPos = ''
  mapState.startPos = ''
  pointList = [];
  list = []
  resetMark();
}

const resetMark = () => {
  pointMarder.c_p_marker.remove()
  pointMarder.s_p_marker.remove()
  pointMarder.e_p_marker.remove()
}

onUnmounted(() => {
  reset();
})





</script>
<style lang="scss" scoped>
.mapping {
  height: 5.18rem;
}
</style>